package com.libbase.widget.imageview;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Shader;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import com.libbase.R;

/**
 * 放大镜
 * Created by admin on 2016/11/28.
 */
public class MirrorImageView extends View {
    private Bitmap bitmap;
    private Paint paint;
    private int width;
    private int height;
    private Bitmap scaleBitmap;
    private int SCALE = 2;//缩放的倍数
    private ShapeDrawable drawable;
    private int radius = 75;//圆的半径
    private Matrix matrix;

    public MirrorImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        matrix = new Matrix();
        paint = new Paint();
        paint.setStrokeWidth(8);
        bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.timg1);
        width = bitmap.getWidth();
        height = bitmap.getHeight();

        scaleBitmap = Bitmap.createScaledBitmap(bitmap, width * SCALE, height * SCALE, true);

        BitmapShader shader = new BitmapShader(scaleBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
        drawable = new ShapeDrawable(new OvalShape());
        drawable.getPaint().setShader(shader);
        //设置drawable显示的区域,这个上面已经说过,不设置区域 图片是显示不出来的
        drawable.setBounds(0, 0, radius * 2, radius * 2);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawBitmap(bitmap, 0, 0, null);
        drawable.draw(canvas);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int x = (int) event.getX();
        int y = (int) event.getY();
        matrix.setTranslate(radius - x * SCALE, radius - y * SCALE);
        drawable.getPaint().getShader().setLocalMatrix(matrix);
        drawable.setBounds(x - radius, y - radius, x + radius, y + radius);
        invalidate();
        return true;
    }
}